-- redis db保存类，稍后可以尝试支持集群
local skynet = require "skynet"
local cjson = require "cjson"
local redis = require 'skynet.db.redis'
local parser = require "parser"
local keysutils = require "keysutils"
local genid = require "genid"
local crypt      = require "skynet.crypt"
local md5 =	require	"md5"

local rediscli

require "skynet.manager"


local CMD = {}

function CMD.checklogin(server, phone, pass)
    if not phone or not pass then
        return false, nil
    end
    local uk = keysutils.get_main_user_key(phone)
    local uid = rediscli:get(uk)
    skynet.error("redisd checklogin uid===>",uid)
    if not uid then
        return false, nil
    end

    local key = keysutils.get_user_pwd_key(phone)
    local password = rediscli:get(key)
    skynet.error("redisd checklogin password===>",password," type password=>",type(password)," pass=>",pass," type pass=>",type(pass))
    if password ~= pass then
        return false, nil
    end

    return true, uid
end

function CMD.register(server,userinfo)
    local openid = userinfo.openid
    local key = keysutils.get_main_user_key(openid)
    local uid = rediscli:get(key)
    if not uid then
        uid = genid.gen(rediscli)
        rediscli:set(key,uid)
    end
    local user = regroup(userinfo)
    -- 注册默认信息
    local mapkey = keysutils.get_main_usermap_key(uid)
    rediscli:hmset(mapkey, table.unpack(parser.serialize(user)))
    -- 插入用户列表
    local ulkey = keysutils.get_zset_key('main','user')
    rediscli:zadd(ulkey,os.time(),uid)

    return true, uid
end

local function loaduser(id)
    local k = keysutils.get_main_usermap_key(id)
    local data = rediscli:hgetall(k)
    --从redis里面读出的数据不是hash map格式的需要变成map
    local user = parser.redis_pack(data)
    return user
end

function CMD.loaduser(id)
    assert(id, "用户ID不能是空")
    local ok, val = pcall(tonumber, id)
    assert(ok, "用户ID不能是空")
    assert(val > 0, "用户ID不能是空")
    local user = loaduser(id)
    return user
end


skynet.start(function()
    skynet.dispatch("lua", function(_, _, command, ...)
        skynet.error("redis despatch command = ", command)
        local f = assert(CMD[command])
        skynet.ret(skynet.pack(f(...)))
    end)

    --链接redis
    local redisconf = {
        host = REDIS_CONF.ip,
        port = REDIS_CONF.port,
        db = 0
    }
    rediscli = redis.connect(redisconf)

    if not rediscli then
        error(" rediscli 连接失败")
    end

    skynet.fork(function()
        while true do
            if true then
                rediscli:ping()
                skynet.sleep(1000)
            end
        end
    end)
    collectgarbage()

    skynet.register "redisd"
end)
